#include "udpsocket.h"

#include <QAbstractSocket>
#include <QHostAddress>

const char *loginstatus[] = { "success" , "username" , "password",nullptr};


udpsocket::udpsocket(const int& part , QObject *parent )
    : QUdpSocket(parent),UDP_PORT(part)
{
    // 绑定到特定端口以接收广播
    if (!bind(QHostAddress::Any,  UDP_PORT)) {
        qDebug() << "Failed to bind UDP socket:" << errorString();
        return;
    }
    // 连接信号和槽
    connect(this, &QUdpSocket::readyRead, this, &udpsocket::processPendingDatagrams );
}

udpsocket::~udpsocket()
{}


/**
 * @brief udpsocket::sendMessage 发送数据
 * @param datagram
 */
void udpsocket::sendMessage( QByteArray datagram )
{
    // 发送数据
    if (writeDatagram(datagram, QHostAddress::Broadcast, UDP_PORT) == -1) {
        qDebug() << "Error sending broadcast:" << errorString();
    } else {
        qDebug() << "Broadcast message sent.";
    }
}
/**
 * @brief processPendingDatagrams 接收数据
 */
void udpsocket::processPendingDatagrams()
{
    while (hasPendingDatagrams())
    {
        QByteArray datagram;
        datagram.resize(int(pendingDatagramSize()));
        QHostAddress senderAddress;
        quint16 senderPort;

        readDatagram(datagram.data(), datagram.size(), &senderAddress, &senderPort);

        QString jsonString =QString::fromUtf8( datagram );
        // 将 JSON 字符串转换为 QJsonDocument
        QJsonDocument jsonDoc = QJsonDocument::fromJson(jsonString.toUtf8());
        // 检查 JSON 文档是否有效
        if (jsonDoc.isNull() || !jsonDoc.isObject())
        {
            continue;
        }
        else
        {
            // 获取 JSON 对象
            QJsonObject jsonObj = jsonDoc.object();
            // 解析 id
            if( 1002 == jsonObj.value("id").toInt())
            {
                QString status = jsonObj.value("status").toString();
                int i =0;
                while( status != nullptr )
                {
                    if( status == loginstatus[i] )
                    {
                        pAccessMessages m_AccessMessages = new AccessMessages;
                        m_AccessMessages->sender = senderAddress;
                        m_AccessMessages->senderPort = senderPort;
                        m_AccessMessages->datagram = QByteArray(loginstatus[i]);
                        emit retUdpMessage( (void*)m_AccessMessages);
                        break;
                    }
                    i++;
                }
            }
        }
    }
}
